package com.zz.load.handle;

import com.zz.load.config.MyServletConfig;
import com.zz.load.http.MyRequestServlet;
import com.zz.load.http.MyResponseServlet;
import com.zz.load.servlet.MyServlet;
import com.zz.load.util.MyPrintWriter;

import java.io.*;
import java.net.Socket;
import java.util.Properties;

public class RequestHandle implements Runnable{
    private Socket socket = null;
    private InputStream inputStream;
    private OutputStream outputStream;

    public RequestHandle(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            InputStreamReader isr = new InputStreamReader(inputStream, "utf-8");
            BufferedReader buf = new BufferedReader(isr);
            String firstStr = buf.readLine();
            MyRequestServlet myRequestServlet = new MyRequestServlet(firstStr);

            MyResponseServlet myResponseServlet = new MyResponseServlet(outputStream);
            String path = myRequestServlet.getPath();

            if(path.endsWith(".html")){
                reHtml(path.substring(1));
            }else{
                MyServlet obj = (MyServlet) MyServletMap.pathMap.get(path);
                MyServletConfig myServletConfig = new MyServletConfig();
//            myServletConfig.setInfo("大家好，我是张哲");
                //obj.init(myServletConfig);
                if(obj != null){
                    obj.service(myRequestServlet, myResponseServlet);
                }
            }

            socket.close();
        } catch (Exception e) {
            MyPrintWriter printWriter = new MyPrintWriter(outputStream);
            printWriter.write("<h1>404 NOT Found</h1>");
            e.printStackTrace();
        }
    }

    public void closeSocket() {
        try {
            this.socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void reHtml(String htmlName) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(htmlName)));
        String buf = null;
        StringBuilder sb = new StringBuilder();
        while ((buf = br.readLine()) != null){
            sb.append(buf);
        }
        MyPrintWriter pw = new MyPrintWriter(outputStream);
        pw.write(sb.toString());
    }
}
